package com.fare.taluo.application.impl.plane.city;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fare.taluo.application.plane.city.CityTreeApplicatioin;
import com.fare.taluo.application.plane.city.ComboTree;
import com.fare.taluo.base.ddd.application.BaseApplicationImpl;
import com.fare.taluo.core.domain.config.city.CityEntity;
import com.fare.taluo.core.domain.config.city.PortEntity;

@Transactional
@Service
public class CityTreeApplicatioinImpl extends BaseApplicationImpl implements CityTreeApplicatioin {
	
	@Override
	public ComboTree getTopCityTree() throws Exception{
		CityEntity root = CityEntity.get(CityEntity.class, ComboTree.ROOT_ID);
		ComboTree rootTree = null;
		if(root != null){
			rootTree = new ComboTree(root);
			this.reloadTree(rootTree);
		}
		return rootTree;
	}
	
	private void reloadTree(ComboTree rootTree) throws Exception {
		//加载地区与城市
		List<CityEntity> allCitys = new CityEntity().findAll();
		List<ComboTree> allTrees  = this.recurrenceChildTree(allCitys, rootTree);
		
		//加载机场
		List<PortEntity> allPorts = new PortEntity().findAll();
		for(ComboTree m : allTrees){
			this.recurrencePortTree(allPorts, m);
		}
		
	}
	
	private List<ComboTree> recurrenceChildTree(List<CityEntity> alls, ComboTree t){
		List<ComboTree> trees = new ArrayList<ComboTree>();
		ComboTree mtf = null;
		for(CityEntity m : alls){
			
			//父节点ID与当前节点ID相同，则放入子集中
			if(m.getPid() != null && m.getPid().intValue() == t.getId().intValue()){
				mtf = new ComboTree(m);
				t.getChildren().add(mtf);
				trees.add(mtf);
				this.recurrenceChildTree(alls, mtf);
			}
		}
		return trees;
	}
	private void recurrencePortTree(List<PortEntity> allPorts, ComboTree t){
		ComboTree mtf = null;
		for(PortEntity m : allPorts){
			//父节点ID与当前节点ID相同，则放入子集中
			if(m.getCityId() != null && m.getCityId() == t.getId()){
				mtf = new ComboTree(m);
				t.getChildren().add(mtf);
			}
		}
	}

}
